package org.theonept.travian.model;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.theonept.travian.util.ConnexionUtil;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable
public class Compte extends Entity {
	@DatabaseField(id = true)
	private Long idCompte;

	@DatabaseField
	private String urlServeur;
	@DatabaseField
	private String username;
	@DatabaseField
	private String password;
	@DatabaseField
	private EnumRace race;
	@DatabaseField
	private boolean etat;
	private List<Village> villages;
	private List<Message> messages;

	public Compte() {
		this.villages = new ArrayList<Village>();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public EnumRace getRace() {
		return race;
	}

	public void setRace(EnumRace race) {
		this.race = race;
	}

	public boolean isEtat() {
		return etat;
	}

	public void setEtat(boolean etat) {
		this.etat = etat;
	}

	public String getUrlServeur() {
		return urlServeur;
	}

	public void setUrlServeur(String urlServeur) {
		this.urlServeur = urlServeur;
	}

	public List<Village> getVillages() {
		if (etat && (villages == null || !isUpToDate())) {
			villages = Village.getVillages(this.getUrlServeur() + "dorf1.php",
					this);
			update();
		}
		return villages;
	}

	public void setVillages(List<Village> villages) {
		this.villages = villages;
	}

	public static void parseCompte(String page, Compte compte) {

		Document first = Jsoup.parse(page);

		compte.setRace(EnumRace.getRaceFromId(first
				.getElementById("sidebarBoxHero")
				.getElementsByAttributeValueStarting("class", "nation").get(0)
				.attr("class")));

	}

	/**
	 * @return the messages
	 */
	public List<Message> getMessages() {
		if (isEtat()) {
			messages = Message.getMessages(this);
		}
		return messages;
	}

	/**
	 * @param messages
	 *            the messages to set
	 */
	public void setMessages(List<Message> messages) {
		this.messages = messages;
	}

	public void disconnect() {
		ConnexionUtil.disconnect(this);
		setEtat(false);

	}

	/**
	 * @return the idCompte
	 */
	public Long getIdCompte() {
		return idCompte;
	}

	/**
	 * @param idCompte
	 *            the idCompte to set
	 */
	public void setIdCompte(Long idCompte) {
		this.idCompte = idCompte;
	}
}
